package com.lemon.cloud.websocket.config;

import com.lemon.cloud.websocket.handler.CustomPlanTextMessageHandler;
import com.lemon.cloud.websocket.handler.CustomWebSocketHandler;
import com.lemon.cloud.websocket.handler.PlanTextMessageHandler;
import com.lemon.cloud.websocket.holder.MapSessionWebSocketHandlerDecorator;
import com.lemon.cloud.websocket.holder.SecuritySessionKeyGenerator;
import com.lemon.cloud.websocket.holder.SessionKeyGenerator;
import com.lemon.cloud.websocket.interceptor.SessionKeyInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;


/**
 * @author HuangDS
 */
@EnableConfigurationProperties({WebSocketProperties.class})
@AllArgsConstructor
@ComponentScan("com.lemon.cloud.websocket.handler")
public class WebSocketHandlerConfig {

    @Bean
    @ConditionalOnMissingBean({SessionKeyGenerator.class})
    public SessionKeyGenerator sessionKeyGenerator() {
        return new SecuritySessionKeyGenerator();
    }

    @Bean
    @ConditionalOnMissingBean({HandshakeInterceptor.class})
    public HandshakeInterceptor handshakeInterceptor() {
        return new SessionKeyInterceptor();
    }

    @Bean
    @ConditionalOnMissingBean({PlanTextMessageHandler.class})
    public PlanTextMessageHandler planTextMessageHandler() {
        return new CustomPlanTextMessageHandler();
    }

    @Bean
    @ConditionalOnBean({PlanTextMessageHandler.class})
    @ConditionalOnMissingBean({TextWebSocketHandler.class})
    public WebSocketHandler webSocketHandler2(@Autowired(required = false) SessionKeyGenerator sessionKeyGenerator,
                                              PlanTextMessageHandler planTextMessageHandler) {
        CustomWebSocketHandler customWebSocketHandler = new CustomWebSocketHandler(planTextMessageHandler);
        return new MapSessionWebSocketHandlerDecorator(customWebSocketHandler, sessionKeyGenerator);
    }
}
